# coding: utf-8
from datetime import datetime
from typing import List
from pathlib import Path

from sqlalchemy import Column, String, TEXT, DATETIME, BOOLEAN
from sqlalchemy.orm import Session

from ...db import DbBase


class TabelCover(DbBase):
    __tablename__ = 'cover'  # 封面表
    cover_url = Column(TEXT, primary_key=True)  # 封面url
    local_path = Column(TEXT)  # 封面本地路径
    create_time = Column(DATETIME, default=datetime.now)  # 创建时间


def cover_exist(cover_url: str, session: Session) -> bool:
    """
    判断封面是否存在
    :param cover_url: 封面url
    :param session: session
    :return: bool
    """
    cover = session.query(TabelCover).filter(TabelCover.cover_url == cover_url).first()  # type: TabelCover
    if cover:
        return True
    else:
        return False


def add_cover(cover_url: str, local_path: str, session: Session) -> bool:
    """
    添加封面
    """
    if cover_exist(cover_url, session):
        return True
    # 保存封面到本地
    cover = TabelCover(cover_url=cover_url, local_path=local_path)
    session.add(cover)
    session.commit()
    return True


def get_cover_path(cover_url: str, session: Session) -> str:
    """
    获取封面路径
    """
    cover = session.query(TabelCover).filter(TabelCover.cover_url == cover_url).first()  # type: TabelCover
    if cover:
        return cover.local_path
    else:
        return cover_url
